/*
 * @Author       : 魏威 <1209562577@qq.com>
 * @Date         : 2022-04-01 10:27 周5
 * @Description  : url 相关方法
 */

import { useMemo } from "react";
import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { cleanObject } from "utils";

export const useUrlParams = <K extends string | number>(keys: K[]) => {
  const [searchParams, setSearchParams] = useSearchParams();

  return [
    useMemo(
      () =>
        keys.reduce(
          (prev, key) => ({
            ...prev,
            [key]: searchParams.get(String(key)),
          }),
          {} as { [key in K]: string }
        ),
      [searchParams]
    ),
    (params: Partial<{ [key in K]: unknown }>) => {
      const o = cleanObject({
        ...Object.fromEntries(searchParams),
        ...params,
      }) as URLSearchParamsInit;
      return setSearchParams(o);
    },
  ] as const;
};
